package com.bestv.search.engine.compass.spellcheck;

import com.bestv.search.common.util.StringConst;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.File;
import java.io.IOException;

public class SpellCheckerWrapper {
    private static SpellChecker spellchecker = null;

    public static void createSpellIndex(String luceneIndexFolder, String field, String spellCheckIndex)
            throws IOException {
        IndexReader reader = null;
        try {
            reader = IndexReader.open(luceneIndexFolder);
            LuceneDictionary dic = new LuceneDictionary(reader, field);
            spellchecker = new SpellChecker(FSDirectory.getDirectory(new File(spellCheckIndex)));
            spellchecker.indexDictionary(dic);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }

    public static void createSpellIndex(String dicFile, String spellCheckIndex) throws IOException {
        spellchecker = new SpellChecker(FSDirectory.getDirectory(new File(spellCheckIndex)));
        spellchecker.indexDictionary(new PlainTextDictionary(new File(dicFile)));
    }

    public static SpellChecker getSpellChecker(String spellCheckIndex) throws IOException {
        if (spellchecker == null) {
            spellchecker = new SpellChecker(FSDirectory.getDirectory(new File(spellCheckIndex)));
        }
        return spellchecker;
    }

    public static SpellChecker getSpellChecker(Directory spellCheckIndexDic) throws IOException {
        if (spellchecker == null) {
            spellchecker = new SpellChecker(spellCheckIndexDic);
        }
        return spellchecker;
    }

    public static String getDicFile() {
        // Create cache folder for save dic
        String dicFolder = SpellCheckerWrapper.class.getClassLoader().getResource(File.separator).getPath()
                + StringConst.CACHE;
        File folder = new File(dicFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }
        return dicFolder + File.separator + StringConst.SPELL_CHECK_DIC;
    }
}